package com.rockcent.mall.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.StdArraySerializers;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.Category;
import com.rockcent.mall.lib.dto.CategoryDto;
import com.rockcent.mall.lib.dto.MallCategoryDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.CategoryRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@RestController
public class MallCategoryController extends BaseController {


    private final Logger log = LoggerFactory.getLogger(MallCategoryController.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private CategoryRepository categoryRepository;

    private final static Integer MAX_VISIBLE_CATEGORY = 20;

    /**
     * @api {get} /mall/category/list 类目 列表
     * @apiGroup mall_category
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} parentId: <code>为空表示查询顶级分类列表，不为空表示该parentId下的子分类列表</code>上一级分类ID
     * @apiParam{Long} leave <code>1,2,3....</code>层级
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     *   "data": [
     *      {
     *       "id": 1,
     *       "dateCreated": "2016-01-15 11:25:00",
     *       "lastUpdated": "2016-11-15 14:38:35",
     *       "name": "美食",
     *       "visible": true,
     *       "displayOrderId": 12,
     *       "mallId": 1,
     *       "hasTowLevel": true,
     *       "hasThreeLevel": false
     *      },
     *      {
     *       "id": 106,
     *       "dateCreated": "2016-06-06 15:44:02",
     *       "lastUpdated": "2016-11-15 14:36:04",
     *       "name": "女装",
     *       "visible": true,
     *       "displayOrderId": 2,
     *       "mallId": 1,
     *       "hasTowLevel": true,
     *       "hasThreeLevel": false
     *      }
     *      ]
     *   }
     */
    @RequestMapping(value = Routes.MALL_CATEGORY_LIST, method = RequestMethod.GET)
    public JsonResult show(CategoryDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getLeave() == null) {
                dto.setLeave(1l);
            }
            List<CategoryDto> resultList = categoryRepository.getCategoryByMallIdAndIsDeleteAndParentId(userInfoDto.mall.getId(), Whether.NO, dto.getLeave(), dto.getParentId());
            resultList.forEach(category -> {
                final boolean hasTowLevel = categoryRepository.findTwoLevel(userInfoDto.mall.getId(), category.getId()).size() > 0;
                category.setHasTowLevel(hasTowLevel);
                if (hasTowLevel) {
                    final boolean hasThreeLevel = categoryRepository.findThreeLevel(userInfoDto.mall.getId(), category.getId()).size() > 0;
                    category.setHasThreeLevel(hasThreeLevel);
                }

            });
            jsonResult.data = resultList;
        };
        return doing.go(request, objectMapper, log);
    }

    /**
     *
     * @api {get} /mall/category/visible/list 可见类目列表
     * @apiGroup mall_category
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} parentId: <code>为空表示查询顶级分类列表，不为空表示该parentId下的子分类列表</code>上一级分类ID
     * @apiParam {Long} leave <code>必传参数 1,2....</code>当前类目所在层级
     * @apiSuccessExample {json} Success-Response:
     * {"
     * code":"1",
     * "desc":"成功",
     * "data":[
     * {
     *    "id":1,
     *    "dateCreated":"2016-01-15 11:25:00",
     *    "lastUpdated":"2016-11-15 14:38:35",
     *    "version":125,
     *    "name":"美食",
     *    "visible":true,
     *    "displayOrderId":12,
     *    "mallId":1
     * },
     * {
     *    "id":106,
     *    "dateCreated":"2016-06-06 15:44:02",
     *    "lastUpdated":"2016-11-15 14:36:04",
     *    "version":26,"name":"女装",
     *    "visible":true,
     *    "displayOrderId":2,
     *    "mallId":1
     * }
     * ]
     * }
     */
    @RequestMapping(value = Routes.MALL_CATEGORY_VISIBLE_LIST, method = RequestMethod.GET)
    public JsonResult showVisibleCategory(CategoryDto dto, HttpServletRequest request) {

        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            Map resultMap = new HashMap<String, Object>();
            if (dto.getLeave() == null) {
                jsonResult.remind("leave 表示当前类目层级数，必须为 1或者2",log);
                return;
            }
            boolean hasTwoLeave = true;
            List<MallCategoryDto> secondCategroys = new ArrayList<MallCategoryDto>();
            secondCategroys = categoryRepository.findVisiableTwoLevel(userInfoDto.mall.getId(), dto.getParentId());
           if(secondCategroys==null ||secondCategroys.isEmpty()){
               hasTwoLeave=false;
           }else {
               boolean hasThirdLeave = false;
               MallCategoryDto category=null;
               List<Long> idxs=new ArrayList<Long>();
               for (Iterator<MallCategoryDto> itr = secondCategroys.iterator(); itr.hasNext(); ) {

                    category = itr.next();
                   if(dto.getLeave()<2) {
                       List<MallCategoryDto> thirdCategroys = categoryRepository.findVisiableTwoLevel(userInfoDto.mall.getId(), category.getId());
                       if (thirdCategroys.isEmpty()) {
                           hasThirdLeave = false;
                           idxs.add(category.getId());
                       } else {
                           hasThirdLeave = true;

                       }
                   }

               }



                   for(Iterator<Long> index=idxs.iterator();index.hasNext();) {
                       Long idx=index.next();
                       for(Iterator<MallCategoryDto> citr = secondCategroys.iterator(); citr.hasNext();){
                           MallCategoryDto del=citr.next();
                           if(del.getId()==idx){
                               citr.remove();
                           }
                       }

                   }

               jsonResult.data=secondCategroys;
           }

        };


        return doing.go(request, objectMapper, log);
    }


    /**
     * @api {post} /mall/category/info  类目 信息
     * @apiGroup mall_category
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id    当前分类ID
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     *   "data": [
     *      {
     *      "id": 64,
     *      "dateCreated": "2016-01-15 11:25:00",
     *      "lastUpdated": "2016-01-15 11:25:00",
     *      "version": 0,
     *      "name": "出境游",
     *      "visible": true,
     *      "displayOrderId": 1,
     *      "mallId": 1,
     *      "parentId": 5
     *      }
     *      ]
     *   }
     */
    @RequestMapping(value = Routes.MALL_CATEGORY_INFO, method = RequestMethod.POST)
    public JsonResult info(@RequestBody CategoryDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            if (dto.getId() != null) {
                Category category = categoryRepository.findByIdAndMallId(dto.getId(), userInfoDto.mall.getId());
                jsonResult.data = category;
            }

        };
        return doing.go(request, objectMapper, log);
    }


    /**
     * @api {post} /mall/category/update 类目 更新
     * @apiGroup mall_category
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam  {Long} id          当前分类ID
     * @apiParam {String} name       分类名称
     * @apiParam {String} iconUrl    类目图标URL
     * @apiParam {Integer} displayOrderId : 显示顺序
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_CATEGORY_UPATE, method = RequestMethod.POST)
    public JsonResult update(@RequestBody CategoryDto categoryDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            if (categoryDto != null) {
                Category category = categoryRepository.findByIdAndMallId(categoryDto.getId(), userInfoDto.mall.getId());
                if (categoryDto.getName() != null && !"".equals(categoryDto.getName())) {
                    category.setName(categoryDto.getName());
                }
                if (categoryDto.getDisplayOrderId() != null) {
                    category.setDisplayOrderId(categoryDto.getDisplayOrderId());
                }

                if (categoryDto.getVisible() != null) {
                    category.setVisible(categoryDto.getVisible());
                }

                if (categoryDto.getIconUrl() != null && !"".equals(categoryDto.getIconUrl())) {
                    category.setIconUrl(categoryDto.getIconUrl());
                }

                categoryRepository.save(category);
            }

        };
        return doing.go(request, log);
    }


    /**
     * @api {post} /mall/category/add 类目 添加
     * @apiGroup mall_category
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain  请求域名
     * @apiParam {String} name     分类名称
     * @apiParam {String} iconUrl  类目图标URL
     * @apiParam {Long} parentId  父级类目ID
     * @apiParam {Integer} displayOrderId  显示顺序 默认 1
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_CATEGORY_ADD, method = RequestMethod.POST)
    public JsonResult add(@RequestBody CategoryDto categoryDto, HttpServletRequest request) {

        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            if (categoryDto != null) {
                Category category = new Category();
                category.setVisible(Boolean.FALSE);
                category.setName(categoryDto.getName());
                category.setIsDelete(Whether.NO);

                category.setIconUrl(categoryDto.getIconUrl());
                category.setMallId(userInfoDto.mall.getId());
                category.setDisplayOrderId(categoryDto.getDisplayOrderId() == null ? 1 : categoryDto.getDisplayOrderId());
                if (categoryDto.getParentId() != null) {
                    category.setParentId(categoryDto.getParentId());
                }
                categoryRepository.save(category);
            }
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /mall/category/status 类目 启用|停用
     * @apiGroup mall_category
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} id  类目ID
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_CATEGORY_STATUS, method = RequestMethod.POST)
    public JsonResult changeStatus(@RequestBody CategoryDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long dtoId = dto.getId();
            if (null == dtoId) {
                jsonResult.remind("类目ID 不能为空",log);
                return;
            }
            Category category = categoryRepository.findOne(dtoId);
            log.info("======================>category:{}", category);
            if (category == null) {
                jsonResult.remind("类目不存在",log);
                return;
            } else {
                Boolean categoryVisible = category.getVisible();
                if (categoryVisible) {
                    List<MallCategoryDto> twoLeaveCategory = categoryRepository.findTwoLevel(userInfoDto.mall.getId(), category.getId());
                    twoLeaveCategory.forEach(mallCategoryDto -> {
                        Category itemCategory = categoryRepository.getOne(mallCategoryDto.getId());
                        itemCategory.setVisible(false);
                        categoryRepository.save(itemCategory);
                    });
                    List<Category> threeLeaveCategory = categoryRepository.findThreeLevel(userInfoDto.mall.getId(), category.getId());
                    threeLeaveCategory.forEach(itemCategory -> {
                        itemCategory.setVisible(false);
                        categoryRepository.save(itemCategory);
                    });
                    category.setVisible(false);
                } else {
                    category.setVisible(true);
                }
                categoryRepository.save(category);
            }
        };
        return doing.go(request, log);
    }


}
